use crate::protocols::{TransportRead, TransportType, TransportWrite, ValueRef};
use crate::Result;
use alloc::vec::Vec;

pub struct MsgpackProtocolBuffer {
    buff: Vec<u8>,
    payload_len: usize,
}

impl MsgpackProtocolBuffer {
    pub fn new(size: usize, tt: TransportType) -> Self {
        assert!(size > 1);
        let mut my = Self {
            buff: Vec::with_capacity(size),
            payload_len: 0,
        };
        // unsafe { my.buff.set_len(size) };
        let flags: u8 = match tt {
            TransportType::Json => 1,
            TransportType::Msgpack | TransportType::Auto => 2,
        };
        my.buff.push(flags);
        my
    }

    pub fn new_reader() -> Self {
        Self {
            buff: Vec::new(),
            payload_len: 0,
        }
    }
    pub fn buff(&mut self) -> &mut [u8] {
        &mut self.buff.as_mut_slice()[..(1 + self.payload_len)]
    }

    pub fn set_flags(&mut self, flags: u8) {
        self.buff[0] = flags;
    }
    pub fn flags(&self) -> u8 {
        self.buff[0]
    }
}

impl TransportWrite for MsgpackProtocolBuffer {
    fn payload(&mut self) -> &mut Vec<u8> {
        &mut self.buff
    }

    fn flush(self) -> Result<Vec<u8>> {
        Ok(self.buff)
    }
}

impl TransportRead for MsgpackProtocolBuffer {
    fn read<'a>(&mut self, _data: &'a [u8]) -> Result<ValueRef<'a>> {
        todo!()
    }
}
